package com.pope.framework.statistics.modular.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pope.framework.constants.Constants;
import com.pope.framework.constants.RescueWhereAboutsEnum;
import com.pope.framework.constants.TriageStatus;
import com.pope.framework.constants.TriageWhereAboutsEnum;
import com.pope.framework.core.reqres.response.ResponseData;
import com.pope.framework.core.util.DateUtil;
import com.pope.framework.core.util.HttpContext;
import com.pope.framework.core.util.MapUtil;
import com.pope.framework.core.util.StringUtil;
import com.pope.framework.dict.modular.entity.DictExamination;
import com.pope.framework.kernel.model.page.PageResult;
import com.pope.framework.page.PageFactory;
import com.pope.framework.rescue.modular.entity.RescueInfo;
import com.pope.framework.rescue.modular.service.RescueInfoService;
import com.pope.framework.statistics.modular.dto.TriageInfoListDto;
import com.pope.framework.statistics.modular.vo.DepartAllNumberVo;
import com.pope.framework.statistics.modular.vo.DepartNumberVo;
import com.pope.framework.statistics.modular.vo.GradeNumberVo;
import com.pope.framework.statistics.modular.vo.TriageDepartWorkloadVo;
import com.pope.framework.statistics.modular.vo.TriageInfoListVo;
import com.pope.framework.statistics.modular.vo.TriageWorkloadVo;
import com.pope.framework.third.ThirdUtil;
import com.pope.framework.triage.modular.entity.TriageInfo;
import com.pope.framework.triage.modular.service.TriageInfoService;
import com.pope.framework.triage.modular.vo.ComplaintClassifyVo;
import com.pope.framework.triage.modular.vo.DictGradeVo;
import com.pope.framework.triage.modular.vo.DictVo;
import com.pope.framework.triage.modular.vo.TriageSimpleInfoVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import jdk.nashorn.internal.objects.annotations.Where;

@RestController
//@CrossOrigin(allowCredentials="true",maxAge = 3600)
@CrossOrigin
@RequestMapping("${spring.application.app-id}/statistics")
@Api(value="统计数据相关API",tags= {"统计数据相关API"})
public class StatisticsInfoController {

	@Autowired
	private TriageInfoService triageInfoService;
	@Autowired
	private RescueInfoService rescueInfoService;
	@Autowired
	private ThirdUtil thirdUtil;
	@ApiOperation(value = "统计就诊人数",notes = "统计就诊人数")
	@GetMapping("patients/number")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="data返回数值为就诊人数数字")
	public ResponseData<Integer> patientsNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		return ResponseData.success(triageInfoService.selectPatientsNumber(beginDate, endDate, hospitalId,"",TriageStatus.YPG.getCode().toString()));
	}
	
	
	@ApiOperation(value = "统计抢救室人数",notes = "统计抢救室人数")
	@GetMapping("emergency/number")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "beginDate",value = "抢救室开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "抢救室结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="data返回数值为抢救室人数数字")
	public ResponseData<Integer> emergencyNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		
		return ResponseData.success(rescueInfoService.selectPatientsNumber(beginDate, endDate, hospitalId,RescueWhereAboutsEnum.QJS));
	}
	
	@ApiOperation(value = "统计留观室人数",notes = "统计留观室人数")
	@GetMapping("watch/number")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="data返回数值为就诊人数数字")
	public ResponseData<Integer> watchNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		return ResponseData.success(rescueInfoService.selectPatientsNumber(beginDate, endDate, hospitalId,RescueWhereAboutsEnum.LGS));
	}
	
	
	@ApiOperation(value = "统计急诊留院患者数",notes = "统计急诊留院患者数")
	@GetMapping("keep/number")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="data返回数值为抢救室人数数字")
	public ResponseData<Integer> keepNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		
		QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		if(hospitalId!=null) {
			queryWrapper.eq("HOSPITAL_ID", hospitalId);
		}
		
		queryWrapper.between("LEFT(UPDATETIME,10)", beginDate, endDate);
		queryWrapper.and(i->i.in("WHERE_ABOUTS",TriageWhereAboutsEnum.LGS.getCode(),TriageWhereAboutsEnum.QJS.getCode()).or(k->k.isNotNull("DEPART").ne( "DEPART", Constants.NULL_VALUE)));
		//queryWrapper.in("WHERE_ABOUTS", TriageWhereAboutsEnum.LGS.getCode(),TriageWhereAboutsEnum.QJS.getCode()).or().();
		queryWrapper.eq("TRIAGE_STATE", TriageStatus.YPG.getCode().toString());
		Integer count=triageInfoService.count(queryWrapper);
		return ResponseData.success(count);
	}
	
	@ApiOperation(value = "统计急诊离院患者数",notes = "统计急诊离院患者数")
	@GetMapping("leave/number")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "Integer",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="统计急诊离院患者数")
	public ResponseData<Integer> leaveNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		
		QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		if(hospitalId!=null) {
			queryWrapper.eq("HOSPITAL_ID", hospitalId);
		}
		
		queryWrapper.between("LEFT(UPDATETIME,10)", beginDate, endDate);
		queryWrapper.in("WHERE_ABOUTS", TriageWhereAboutsEnum.HJ.getCode(),TriageWhereAboutsEnum.ZY.getCode());
		queryWrapper.eq("TRIAGE_STATE", TriageStatus.YPG.getCode().toString());
		Integer count=triageInfoService.count(queryWrapper);
		return ResponseData.success(count);
	}
	
	
	@ApiOperation(value = "统计急诊病人分布情况",notes = "统计急诊病人分布情况")
	@GetMapping("emergency/patient/distribution")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1")     
	 })
	
	public ResponseData<List<DepartAllNumberVo>> patientDistribution(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		
		List<Map<String,Object>> qjsDatas=MapUtil.changeKeyToLower(rescueInfoService.selectDepartPatientsNumber(beginDate, endDate, hospitalId, RescueWhereAboutsEnum.QJS));
		List<Map<String,Object>> lgsDatas=MapUtil.changeKeyToLower(rescueInfoService.selectDepartPatientsNumber(beginDate, endDate, hospitalId, RescueWhereAboutsEnum.LGS));
		List<Map<String,Object>> departs=thirdUtil.getDeparts(hospitalId);
		List<DepartAllNumberVo> departAllNumberVos=CollUtil.newArrayList();
//		QueryWrapper<TriageInfo> queryTriageInfoWrapper=new QueryWrapper<>();
//		queryTriageInfoWrapper.groupBy("DEPART");
//		queryTriageInfoWrapper.select("DEPART,COUNT(0) AS NUM ");
//		if(hospitalId!=null) {
//			queryTriageInfoWrapper.eq("HOSPITAL_ID", hospitalId);
//		}
//		queryTriageInfoWrapper.between("LEFT(UPDATETIME,10)", beginDate, endDate);
		List<DepartNumberVo> list=triageInfoService.selectPatientsNumberByDepart(beginDate, endDate, hospitalId,TriageStatus.YPG.getCode().toString());
		if(CollUtil.isNotEmpty(departs)) {
			for(Map<String,Object> depart:departs) {
				String departId=StringUtil.toStr(depart.get("id"));
				DepartAllNumberVo departAllNumberVo=new DepartAllNumberVo();
				departAllNumberVo.setDepart(StringUtil.toInt(depart.get("id")));
				departAllNumberVo.setDepartName(StringUtil.toStr(depart.get("name")));
				departAllNumberVo.setTriageNumber(getDepartNumber2(departId,list));
				departAllNumberVo.setEmergencyNumber(getNumber(departId, qjsDatas));
				departAllNumberVo.setKeepWatchNumber(getNumber(departId, lgsDatas));
				departAllNumberVos.add(departAllNumberVo);
			}
		}
		return ResponseData.success(departAllNumberVos);
	}
	
	private Integer getDepartNumber2(String depart,List<DepartNumberVo> list) {
		if(CollUtil.isNotEmpty(list)) {
			for(DepartNumberVo triageData:list) {
				if(StringUtil.toStr(triageData.getDepart()).equals(depart)) {
					return triageData.getNumber();
				}
			}
		}
		return null;
	}
	private Integer getNumber(String depart,List<Map<String,Object>> datas) {
		if(CollUtil.isNotEmpty(datas)) {
			for(Map<String,Object> triageData:datas) {
				if(StringUtil.toStr(triageData.get("depart")).equals(depart)) {
					return StringUtil.toInt(triageData.get("num"));
				}
			}
		}
		return null;
	}
	
	@ApiOperation(value = "统计科室排队情况",notes = "统计科室排队情况")
	@GetMapping("depart/number")
	 @ApiImplicitParams({
         
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1")     
	 })
	
	@ApiResponse(code=1,message="data返回数值为就诊人数数字")
	public ResponseData<List<DepartNumberVo>> departNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
		}
		
		List<DepartNumberVo> list=triageInfoService.selectPatientsNumberByDepart(beginDate, endDate, hospitalId,TriageStatus.YPG.getCode().toString());
		
		return ResponseData.success(list);
	}
	@ApiOperation(value = "根据分级统计人数信息",notes = "根据分级统计人数信息")
	@GetMapping("grade/number")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd hh:mi，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd hh:mi，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1")     
	 })
	@ApiResponse(code=1,message="data返回数值为就诊人数数字")
	public ResponseData<List<GradeNumberVo>> gradeNumber(String beginDate,String endDate,Integer hospitalId){
		if(StrUtil.isEmpty(beginDate)) {
			beginDate=DateUtil.getCurrentDateStr();
			beginDate=beginDate+" 00:00:00";
		}
		if(StrUtil.isEmpty(endDate)) {
			endDate=DateUtil.getCurrentDateStr();
			endDate=endDate+=" 23:59:59";
		}
		
		List<GradeNumberVo> values=triageInfoService.selectPatientsNumberByGrade(beginDate, endDate, hospitalId,TriageStatus.YPG.getCode().toString());
		 values.sort(new Comparator<GradeNumberVo>() {

				@Override
				public int compare(GradeNumberVo o1, GradeNumberVo o2) {
					if(o1.getNumber()>o2.getNumber()) {
						return -1;
					}else if(o1.getNumber()<o2.getNumber()) {
						return 1;
					}else {
						return 0;
					}
				}
			});
		return ResponseData.success(values);
	}
	
	
	@ApiOperation(value = "分页查询分诊明细列表",notes = "分页查询分诊明细列表")
	@GetMapping("triage/list")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "pagestart",value = "第几页，从1开始，默认为1",dataType = "String",paramType = "query",example = "1"),
         @ApiImplicitParam(name = "pagenum",value = "每页显示记录数，默认为20",dataType = "String",paramType = "query",example = "10"),
         @ApiImplicitParam(name = "orderby",value = "排序字段，默认为主键ID，可排序字段有用ID（分诊主键）,EMERGENCY_NUMBER(分诊编号),PATIENT_ID(患者主键)，CHANGE_GRADE(分级),WHERE_ABOUTS(去向编号)，DEPART（部门ID）,CREATETIME(分诊创建时间),UPDATETIME(分诊最后更新时间)",dataType = "String",paramType = "query",example = "id"),
         @ApiImplicitParam(name = "sort",value = "排序方式，有asc,desc,默认为主键asc",dataType = "String",paramType = "query",example = "desc"),
	})
	public ResponseData<PageResult<TriageInfoListVo>> triageList(TriageInfoListDto triageInfoListDto){
		Page<TriageInfoListVo> page=PageFactory.defaultPage();
		IPage<TriageInfoListVo> datas=triageInfoService.selectTriageStaticsDetail(page, triageInfoListDto);
		return ResponseData.success(PageFactory.pageResult(datas));
	}
	
	@ApiOperation(value = "分诊工作量统计",notes = "分诊工作量统计")
	@GetMapping("triage/workload")
	 @ApiImplicitParams({
		 @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd hh:mi，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd hh:mi，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "triageState",value = "分诊状态1是待评估 2是已评估",dataType = "String",paramType = "query",example = "1"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1")         
	})
	public ResponseData<TriageWorkloadVo> triageList(String beginDate,String endDate,Integer hospitalId,String triageState){
		QueryWrapper<TriageInfo> queryWrapper=new QueryWrapper<>();
		if(hospitalId!=null) {
			queryWrapper.eq("HOSPITAL_ID", hospitalId);
		}
		if(StrUtil.isNotBlank(beginDate)) {
			queryWrapper.ge("UPDATETIME",beginDate);
		}
		if(StrUtil.isNotBlank(endDate)) {
			queryWrapper.le("UPDATETIME", endDate);
		}
		if(StrUtil.isNotBlank(triageState)) {
			queryWrapper.eq("TRIAGE_STATE", triageState);
		}
		queryWrapper.select("DEPART","COUNT(0) AS NUM");
		queryWrapper.groupBy("DEPART");
		List<Map<String,Object>> datas=MapUtil.changeKeyToLower(triageInfoService.listMaps(queryWrapper));
		List<TriageDepartWorkloadVo> departWorkloadVos=CollUtil.newArrayList();
		//List<Map<String,Object>> departs=MapUtil.changeKeyToLower(thirdUtil.getDeparts(hospitalId));
		List<Map<String,Object>> departs=thirdUtil.getDepartsPeople(hospitalId);
		int triageTotalNum=0;
		int doctorTotalNum=0;
		int nurseTotalNum=0;
		if(CollUtil.isNotEmpty(departs)) {
			for(Map<String,Object> depart:departs) {
				String departId=StringUtil.toStr(depart.get("id"));
				String departName=StringUtil.toStr(depart.get("name"));
				String remark=StringUtil.toStr(depart.get("remark"));
				
				TriageDepartWorkloadVo triageDepartWorkloadVo=new TriageDepartWorkloadVo();
				departWorkloadVos.add(triageDepartWorkloadVo);
				triageDepartWorkloadVo.setDepart(StringUtil.toInt(departId));
				triageDepartWorkloadVo.setDepartName(departName);
				if(StrUtil.isNotEmpty(remark)) {
					Map<String,Object> mapRemark=JSONUtil.parseObj(remark);
					if(CollUtil.isNotEmpty(mapRemark)) {
						triageDepartWorkloadVo.setDoctorNum(StringUtil.toInt(mapRemark.get("doctornum")));
						triageDepartWorkloadVo.setNurseNum(StringUtil.toInt(mapRemark.get("nursenum")));
						doctorTotalNum+=triageDepartWorkloadVo.getDoctorNum();
						nurseTotalNum+=triageDepartWorkloadVo.getNurseNum();
					}
				}
				if(CollUtil.isNotEmpty(datas)) {	
					for(Map<String,Object> map:datas) {
						String newDepartId=StringUtil.toStr(map.get("depart"));
						if(departId.equals(newDepartId)) {
							triageDepartWorkloadVo.setTriageNum(StringUtil.toInt(map.get("num")));
							triageTotalNum+=triageDepartWorkloadVo.getTriageNum();
							break;
						}
					}
				}
			}
		}
		TriageWorkloadVo triageWorkloadVo=new TriageWorkloadVo();
		triageWorkloadVo.setBeginDate(beginDate);
		triageWorkloadVo.setEndDate(endDate);
		triageWorkloadVo.setDepartWorkload(departWorkloadVos);
		triageWorkloadVo.setTriageTotalNum(triageTotalNum);
		triageWorkloadVo.setNurseTotalNum(nurseTotalNum);
		triageWorkloadVo.setDoctorTotalNum(doctorTotalNum);
		return ResponseData.success(triageWorkloadVo);
	}
	
	@ApiOperation(value = "查询所有分诊明细列表",notes = "查询所有分诊明细列表")
	@GetMapping("triage/all")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "pagestart",value = "第几页，从1开始，默认为1",dataType = "String",paramType = "query",example = "1"),
         @ApiImplicitParam(name = "pagenum",value = "每页显示记录数，默认为20",dataType = "String",paramType = "query",example = "10"),
         @ApiImplicitParam(name = "orderby",value = "排序字段，默认为主键ID，可排序字段有用ID（分诊主键）,EMERGENCY_NUMBER(分诊编号),PATIENT_ID(患者主键)，CHANGE_GRADE(分级),WHERE_ABOUTS(去向编号)，DEPART（部门ID）,CREATETIME(分诊创建时间),UPDATETIME(分诊最后更新时间)",dataType = "String",paramType = "query",example = "id"),
         @ApiImplicitParam(name = "sort",value = "排序方式，有asc,desc,默认为主键asc",dataType = "String",paramType = "query",example = "desc"),
	})
	public ResponseData<List<TriageInfoListVo>> triageAll(TriageInfoListDto triageInfoListDto){
		Page<TriageInfoListVo> page=PageFactory.defaultPage();
		page.setTotal(1000000L);
		page.setCurrent(1);
		IPage<TriageInfoListVo> datas=triageInfoService.selectTriageStaticsDetail(page, triageInfoListDto);
		
		return ResponseData.success(datas.getRecords());
	}
	
	 /**
	  * 分级变更率统计
	  */
	@ApiOperation(value = "分级变更率统计",notes = "分级变更率统计")
	@GetMapping("triage/perChangeGrage")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "beginDate",value = "开始时间",dataType = "String",paramType = "query",example = "2019-01-02 00:01:02"),
         @ApiImplicitParam(name = "endDate",value = "结束时间",dataType = "String",paramType = "query",example = "2019-01-02 00:01:02"),
         @ApiImplicitParam(name = "hospitalId",value = "所在医院ID",dataType = "String",paramType = "query",example = "1"),
         @ApiImplicitParam(name = "triageState",value = "分诊状态",dataType = "String",paramType = "query",example = "1待评估 2已评估"),
	})
	public ResponseData< Map<String,Object>> selectPerChangeGrage(String beginDate,String endDate,Integer hospitalId,String triageState ){
		return ResponseData.success(triageInfoService.selectPerChangeGrage(beginDate, endDate,hospitalId,triageState));
	}
	
	 /**
	  * 分级变更率统计
	  */
	@ApiOperation(value = "生命特征值完整率",notes = "生命特征值完整率")
	@GetMapping("triage/perNorm")
	 @ApiImplicitParams({
        @ApiImplicitParam(name = "beginDate",value = "开始时间",dataType = "String",paramType = "query",example = "2019-01-02 00:01:02"),
        @ApiImplicitParam(name = "endDate",value = "结束时间",dataType = "String",paramType = "query",example = "2019-01-02 00:01:02"),
        @ApiImplicitParam(name = "hospitalId",value = "所在医院ID",dataType = "String",paramType = "query",example = "1"),
        @ApiImplicitParam(name = "triageState",value = "分诊状态",dataType = "String",paramType = "query",example = "1待评估 2已评估"),
	})
	 public ResponseData<List<Map<String,Object>>> getNormBl(String beginDate,String endDate,Integer hospitalId,String triageState){
		 return ResponseData.success(triageInfoService.getNormBl(beginDate, endDate, hospitalId, triageState));
	 }
	
	@ApiOperation(value = "导出所有分诊明细列表",notes = "导出所有分诊明细列表")
	@GetMapping("triage/excel")
	public void triageExcel(TriageInfoListDto triageInfoListDto) throws Exception{
		Page<TriageInfoListVo> page=PageFactory.defaultPage();
		page.setTotal(1000000L);
		page.setCurrent(1);
		List<String> header=CollUtil.newArrayList("");
		IPage<TriageInfoListVo> datas=triageInfoService.selectTriageStaticsDetail(page, triageInfoListDto);
		  //创建工作薄(excel)
		  Workbook wb = new HSSFWorkbook();
		  //创建sheet
		  Sheet createSheet = wb.createSheet("sheet1");
		  createSheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0));
		  createSheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 5));
		  createSheet.addMergedRegion(new CellRangeAddress(0, 0, 6, 9));
		  createSheet.addMergedRegion(new CellRangeAddress(0, 0, 10, 11));
		  //填充第一行数据
		  Row rowTitle = createSheet.createRow(0);
		  Cell cellTitle1 = rowTitle.createCell(0);
		  cellTitle1.setCellValue("急诊就诊编号");
		  Cell cellTitle2 = rowTitle.createCell(1);
		  cellTitle2.setCellValue("患者基本信息");
		  Cell cellTitle3 = rowTitle.createCell(6);
		  cellTitle3.setCellValue("分诊信息");
		  Cell cellTitle4 = rowTitle.createCell(10);
		  cellTitle4.setCellValue("诊断信息");
		  
		  
		  Row rowTitle1 = createSheet.createRow(1);
		  Cell cellTitle11 = rowTitle1.createCell(1);
		  cellTitle11.setCellValue("患者姓名");
		  Cell cellTitle12 = rowTitle1.createCell(2);
		  cellTitle12.setCellValue("性别");
		  Cell cellTitle13 = rowTitle1.createCell(3);
		  cellTitle13.setCellValue("年龄");
		  Cell cellTitle14 = rowTitle1.createCell(4);
		  cellTitle14.setCellValue("身份证号");
		  Cell cellTitle15 = rowTitle1.createCell(5);
		  cellTitle15.setCellValue("联系电话");
		  Cell cellTitle16 = rowTitle1.createCell(6);
		  cellTitle16.setCellValue("分诊级别");
		  Cell cellTitle17 = rowTitle1.createCell(7);
		  cellTitle17.setCellValue("分诊去向");
		  Cell cellTitle18 = rowTitle1.createCell(8);
		  cellTitle18.setCellValue("分诊科室");
		  Cell cellTitle19 = rowTitle1.createCell(9);
		  cellTitle19.setCellValue("就诊时间");
		  Cell cellTitle20 = rowTitle1.createCell(10);
		  cellTitle20.setCellValue("意识状态");
		  Cell cellTitle21 = rowTitle1.createCell(11);
		  cellTitle21.setCellValue("检伤依据");
		  
		  if(datas!=null && CollUtil.isNotEmpty(datas.getRecords())) {
			  int i=1;
			  for(TriageInfoListVo vo:datas.getRecords()) {
				  i++;
				  Row rowValue = createSheet.createRow(i);
				  
				  Cell cellValue1 = rowValue.createCell(0);
				  cellValue1.setCellValue(StringUtil.toStr(vo.getEmergencyNumber()));
				  Cell cellValue2 = rowValue.createCell(1);
				  cellValue2.setCellValue(StringUtil.toStr(vo.getPatientName()));
				  Cell cellValue3 = rowValue.createCell(2);
				  cellValue3.setCellValue(StringUtil.toStr(vo.getSex()));
				  
				  Cell cellValue4 = rowValue.createCell(3);
				  cellValue4.setCellValue(StringUtil.toStr(vo.getAge()));
				  
				  Cell cellValue5 = rowValue.createCell(4);
				  cellValue5.setCellValue(StringUtil.toStr(vo.getIdNumber()));
				  
				  Cell cellValue6 = rowValue.createCell(5);
				  cellValue6.setCellValue(StringUtil.toStr(vo.getTelephone()));
				  Cell cellValue7 = rowValue.createCell(6);
				  String gradeName="";
				  if(StringUtil.toInt(vo.getChangeGrade(),0)!=0) {
					  gradeName=vo.getChangeGradeName();
				  }else {
					  gradeName=vo.getComingGradeName();
				  }
				  cellValue7.setCellValue(gradeName);
				  
				  Cell cellValue8 = rowValue.createCell(7);
				  cellValue8.setCellValue(StringUtil.toStr(vo.getWhereAboutsName()));
				  
				  Cell cellValue9 = rowValue.createCell(8);
				  cellValue9.setCellValue(StringUtil.toStr(vo.getDepartName()));
				  
				  Cell cellValue10 = rowValue.createCell(9);
				  cellValue10.setCellValue(StringUtil.toStr(vo.getUpdateTime()));
				  
				  Cell cellValue11 = rowValue.createCell(10);
				  cellValue11.setCellValue(StringUtil.toStr(vo.getConsciousStateName()));
				  
				  Cell cellValue12 = rowValue.createCell(11);
				  List<DictGradeVo> dictExaminations=vo.getDictExaminatons();
				  String examinationNames="";
				  if(CollUtil.isNotEmpty(dictExaminations)) {
					  for(DictGradeVo ex:dictExaminations) {
						  examinationNames+=","+ex.getName();
					  }
					  examinationNames=examinationNames.substring(1);
				  }
				  cellValue12.setCellValue(examinationNames);
				  
			  }
		  }
		  // 弹出保存框方式
	        ByteArrayOutputStream os = new ByteArrayOutputStream();
	        wb.write(os);
	        byte[] content = os.toByteArray();
	        InputStream is = new ByteArrayInputStream(content);
	        // 设置response参数，可以打开下载页面
	        
	        HttpContext.getResponse().reset();
	        HttpContext.getResponse().setContentType("application/vnd.ms-excel;charset=utf-8");
	        HttpContext.getResponse().setHeader("Content-Disposition","attachment;filename=" + new String(("分诊明细.xls").getBytes(), "iso-8859-1"));
	       
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        try {
	        	 ServletOutputStream out = HttpContext.getResponse().getOutputStream();
	            bis = new BufferedInputStream(is);
	            bos = new BufferedOutputStream(out);
	            byte[] buff = new byte[2048];
	            int bytesRead;
	            // Simple read/write loop.
	            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	                bos.write(buff, 0, bytesRead);
	            }
	        } catch (Exception e) {
	            // TODO: handle exception
	            e.printStackTrace();
	        } finally {
	        	try {
	            if (bis != null)
	                bis.close();
	            if (bos != null)
	                bos.close();
	        	}catch(Exception ee) {
	        		ee.printStackTrace();
	        	}
	        }
	        //return ResponseData.success();
		//return ResponseData.success(datas.getRecords());
	}
	
	@ApiOperation(value = "根据分级统计人数信息(统计画面专用)",notes = "根据分级统计人数信息(统计画面专用)")
	@GetMapping("grade/number/new")
	 @ApiImplicitParams({
         @ApiImplicitParam(name = "beginDate",value = "分诊开始时间，格式为yyyy-MM-dd hh:mi:mm，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "endDate",value = "分诊结束时间,格式为yyyy-MM-dd hh:mi:mm，如果为空，则取服务器当天日期",dataType = "String",paramType = "query",example = "2018-01-02"),
         @ApiImplicitParam(name = "hospitalId",value = "登陆用户所在医院ID",dataType = "String",paramType = "query",example = "1"),
         @ApiImplicitParam(name = "triageState",value = "分诊状态",dataType = "String",paramType = "query",example = "1")
	 })
	@ApiResponse(code=1,message="data返回数值为就诊人数数字")
	public ResponseData<List<GradeNumberVo>> gradeNumberNew(String beginDate,String endDate,Integer hospitalId,String triageState){
//		if(StrUtil.isEmpty(beginDate)) {
//			beginDate=DateUtil.getCurrentDateStr();
//			beginDate=beginDate+" 00:00:00";
//		}
//		if(StrUtil.isEmpty(endDate)) {
//			endDate=DateUtil.getCurrentDateStr();
//			endDate=endDate+=" 23:59:59";
//		}
		return ResponseData.success(triageInfoService.selectPatientsNumberByGrade(beginDate, endDate, hospitalId,triageState));
	}
	
}
